<template>
  <div class="component-list">
    <h2 class="title">组件列表</h2>
    
    <!-- 组件容器 -->
    <div class="components-container">
      <!-- 数据结构组件 -->
      <div class="component-category">
        <div class="category-header">
        <h3>数据结构</h3>
          <el-button type="primary" link @click="addDialogVisible = true; newComponent.category = 'dataStructure'">
            <el-icon><plus /></el-icon>
          </el-button>
        </div>
        <el-card class="box-card">
          <draggable 
            :list="dataStructures" 
            :clone="cloneComponent"
            :group="{
              name: 'components',
              pull: 'clone',
              put: false
            }"
            item-key="id"
            :sort="false"
          >
            <template #item="{ element }">
              <div class="component-item" 
                :class="{ disabled: element.disabled }"
                draggable="true"
                @dragstart="(e) => handleDragStart(e, element)"
                @dblclick="showVisualization(element)"
              >
                <div class="component-content">
                <el-icon><component :is="element.icon"/></el-icon>
                <span>{{ element.name }}</span>
                </div>
                <el-button 
                  v-if="element.category === 'dataStructure'"
                  type="danger" 
                  link 
                  @click.stop="handleDelete(element)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </template>
          </draggable>
        </el-card>
      </div>

      <!-- 算法组件 -->
      <div class="component-category">
        <div class="category-header">
        <h3>算法</h3>
          <el-button type="primary" link @click="addDialogVisible = true; newComponent.category = 'algorithm'">
            <el-icon><plus /></el-icon>
          </el-button>
        </div>
        <el-card class="box-card">
          <draggable 
            :list="algorithms" 
            :clone="cloneComponent"
            :group="{
              name: 'components',
              pull: 'clone',
              put: false
            }"
            item-key="id"
            :sort="false"
          >
            <template #item="{ element }">
              <div class="component-item" 
                :class="{ disabled: element.disabled }"
                draggable="true"
                @dragstart="(e) => handleDragStart(e, element)"
              >
                <div class="component-content">
                <el-icon><component :is="element.icon"/></el-icon>
                <span>{{ element.name }}</span>
                </div>
                <el-button 
                  v-if="element.category === 'algorithm'"
                  type="danger" 
                  link 
                  @click.stop="handleDelete(element)"
                >
                  <el-icon><Delete /></el-icon>
                </el-button>
              </div>
            </template>
          </draggable>
        </el-card>
      </div>
    </div>

    <!-- 添加组件对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      :title="newComponent.category === 'dataStructure' ? '添加数据结构' : '添加算法'"
      width="30%"
    >
      <el-form :model="newComponent" label-width="100px">
        <el-form-item label="名称">
          <el-input v-model="newComponent.name" placeholder="请输入组件名称" />
        </el-form-item>
        <el-form-item label="图标">
          <el-select v-model="newComponent.icon" placeholder="请选择图标">
            <el-option label="菜单" value="Menu" />
            <el-option label="列表" value="List" />
            <el-option label="搜索" value="Search" />
            <el-option label="排序" value="Sort" />
            <el-option label="连接" value="Connection" />
            <el-option label="文件" value="Files" />
            <el-option label="操作" value="Operation" />
            <el-option label="分享" value="Share" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAddComponent">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 数据结构可视化对话框 -->
    <el-dialog
      v-model="visualizerVisible"
      :title="currentComponent?.name + '可视化'"
      width="80%"
      :before-close="handleVisualizerClose"
      destroy-on-close
      class="visualizer-dialog"
    >
      <DataStructureVisualizer
        v-if="visualizerVisible"
        :type="currentComponent?.type"
        :max-size="10"
        :key="visualizerId"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref } from 'vue'
import draggable from 'vuedraggable'
import { useComponentStore } from '../stores/component'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import DataStructureVisualizer from './DataStructureVisualizer.vue'

const componentStore = useComponentStore()
const addDialogVisible = ref(false)
const newComponent = ref({
  name: '',
  icon: 'Menu',
  category: ''
})

// 当前画布中的数据结构类型
const currentDataStructure = ref(null)

// 可视化相关
const visualizerVisible = ref(false)
const currentComponent = ref(null)
const visualizerId = ref(0)

// 分类组件
const dataStructures = computed(() => 
  componentStore.components.filter(c => {
    const predefinedTypes = [
    'adjacencyMatrix',
    'adjacencyList',
    'array',
    'binaryTree',
    'heap',
    'stack',
    'queue'
    ]
    return predefinedTypes.includes(c.type) || c.category === 'dataStructure'
  }).map(c => ({
    ...c,
    disabled: currentDataStructure.value && currentDataStructure.value !== c.type
  }))
)

// 获取当前数据结构可用的算法类型
const getAvailableAlgorithms = (dataStructureType) => {
  const rules = componentStore.connectionRules[dataStructureType]
  return rules ? rules.outputs : []
}

const algorithms = computed(() => 
  componentStore.components.filter(c => {
    const predefinedTypes = [
    'dijkstra',
    'bubbleSort',
    'bfs',
    'quickSort',
    'dfs',
    'mergeSort',
    'prim',
    'kruskal',
    'binarySearch'
    ]
    return predefinedTypes.includes(c.type) || c.category === 'algorithm'
  }).map(c => ({
    ...c,
    disabled: currentDataStructure.value && 
             !getAvailableAlgorithms(currentDataStructure.value).includes(c.type)
  }))
)

const cloneComponent = (comp) => {
  if (comp.disabled) {
    return null
  }
  return {
    ...comp,
    id: `${comp.type}_${Date.now()}`
  }
}

const handleDragStart = (event, component) => {
  if (component.disabled) {
    event.preventDefault()
    return
  }

  try {
    event.dataTransfer.effectAllowed = 'copy'
    event.dataTransfer.setData('application/json', JSON.stringify(component))

    // 如果是数据结构，设置为当前数据结构
    if (component.category === 'dataStructure' || [
      'adjacencyMatrix',
      'adjacencyList',
      'array',
      'binaryTree',
      'heap',
      'stack',
      'queue'
    ].includes(component.type)) {
      currentDataStructure.value = component.type
    }
  } catch (error) {
    console.warn('拖拽开始时设置数据失败:', error)
  }
}

// 重置当前数据结构（当画布被清空时调用）
const resetCurrentDataStructure = () => {
  currentDataStructure.value = null
}

const handleDelete = (component) => {
  ElMessageBox.confirm(
    `确定要删除 ${component.name} 吗？`,
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    // 从 store 中删除组件
    const index = componentStore.components.findIndex(c => c.id === component.id)
    if (index !== -1) {
      componentStore.components.splice(index, 1)
      ElMessage.success('删除成功')
    }
  }).catch(() => {
    // 用户点击取消，不做任何操作
  })
}

const handleAddComponent = () => {
  if (!newComponent.value.name || !newComponent.value.category) {
    ElMessage.warning('请填写组件名称')
    return
  }

  const type = newComponent.value.name.toLowerCase().replace(/\s+/g, '-')
  
  // 创建新组件
  const comp = {
    id: Date.now(),
    type: type,
    name: newComponent.value.name,
    icon: newComponent.value.icon,
    category: newComponent.value.category,
    config: {}
  }

  // 直接修改 store 中的数组
  componentStore.components.push(comp)

  ElMessage.success('添加成功')
  addDialogVisible.value = false
  newComponent.value = {
    name: '',
    icon: 'Menu',
    category: ''
  }
}

const showVisualization = (component) => {
  if (component.disabled) return
  currentComponent.value = component
  visualizerId.value = Date.now() // 每次打开生成新的ID
  visualizerVisible.value = true
}

const handleVisualizerClose = () => {
  visualizerVisible.value = false
  // 延迟清空currentComponent，确保对话框完全关闭后再重置
  setTimeout(() => {
    currentComponent.value = null
  }, 300)
}

// 定义props接收画布清空事件
const props = defineProps({
  onCanvasCleared: {
    type: Function,
    default: () => {}
  }
})

// 监听画布清空事件的处理函数
const handleCanvasCleared = () => {
  resetCurrentDataStructure()
}

// 向父组件暴露方法
defineExpose({
  handleCanvasCleared
})
</script>

<style scoped lang="scss">
.component-list {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .title {
    margin: 0 0 20px;
    font-size: 20px;
    font-weight: 600;
    color: #2c3e50;
  }

  .components-container {
    flex: 1;
    overflow-y: auto;
    padding-right: 8px;
    
    /* 自定义滚动条样式 */
    &::-webkit-scrollbar {
      width: 6px;
    }
    
    &::-webkit-scrollbar-thumb {
      background-color: #dcdfe6;
      border-radius: 3px;
    }
    
    &::-webkit-scrollbar-track {
      background-color: #f5f7fa;
    }
  }

  .component-category {
    padding-bottom: 20px;
    
    .category-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin: 0 0 10px;
      
      h3 {
        margin: 0;
      font-size: 16px;
      color: #606266;
      }
    }
  }
  
  .component-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10px;
    margin: 5px 0;
    cursor: move;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    user-select: none;
    background: white;
    transition: all 0.3s;
    
    &.disabled {
      opacity: 0.5;
      cursor: not-allowed;
      background-color: #f5f7fa;
    
    &:hover {
        background-color: #f5f7fa;
        border-color: #dcdfe6;
      }
    }
    
    &:not(.disabled):hover {
      background-color: #ecf5ff;
      border-color: #409eff;
    }

    .component-content {
      display: flex;
      align-items: center;
      flex: 1;
    
    .el-icon {
      margin-right: 8px;
      font-size: 18px;
      color: #409eff;
    }
  }

    .el-button {
      padding: 2px;
      margin-left: 8px;
      
      .el-icon {
        font-size: 16px;
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.visualizer-dialog :deep(.el-dialog__body) {
  padding: 0;
  min-height: 400px;
}

.component-item {
  cursor: pointer;
  transition: all 0.3s;
}

.component-item:not(.disabled):hover {
  transform: scale(1.05);
  background-color: #ecf5ff;
}

.component-item:not(.disabled):active {
  transform: scale(0.95);
}
</style> 